package com.hxx.widget.richtext

import android.text.Editable
import android.text.Spanned
import android.text.style.CharacterStyle

/**
 * 分割指定区域样式，123[456]789，样式沿用起始位置前的样式
 *  123:
 */
fun Editable.splitCharacterSpan(start: Int, end: Int = start, keep: Boolean = false) {
    val characterSpans = getSpans(start - 1, start, CharacterStyle::class.java)
    characterSpans.forEach {
        val spanStart = getSpanStart(it) //span 开始索引
        val spanEnd = getSpanEnd(it) //span 结束索引
        val headSpan = SpanFactory.copySpan(it)
        val footSpan = it
        if (spanEnd == start) {
            removeSpan(it)
            setSpan(
                headSpan,
                spanStart,
                start,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            if (spanEnd > start) {
                setSpan(
                    footSpan,
                    end,
                    spanEnd,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
            if (keep) {
                val keepSpan = SpanFactory.copySpan(it)
                setSpan(
                    keepSpan,
                    start,
                    end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
    }
}